package com.abc.robot01.activity.compose

import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.DisplayMode
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SelectableDates
import androidx.compose.material3.Slider
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.Center
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Popup
import androidx.navigation.ui.AppBarConfiguration
import com.abc.robot01.databinding.ActivityMainBinding
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.time.DayOfWeek
import java.time.Instant
import java.time.ZoneId
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.TimeZone


//https://github.com/android/compose-samples
//https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/material3/material3/samples/src/main/java/androidx/compose/material3/samples/DatePickerSamples.kt

class ComposeActivity01 : ComponentActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityMainBinding

    // Extension function to convert pixels to dp
    fun Float.toDp(): Dp = (this / 320).dp


    // Extension function to convert pixels to dp
    fun Double.toDp(): Dp = (this / 320).dp

    // Extension function to convert dp to pixels
    fun Dp.toPx(): Float = (this.value * 320)

//    @Composable
//    fun CircularLayout() {
//        val items = listOf("1", "2", "3", "4", "5")
//        val radius = 100.dp.toPx() // Circle radius
//        val center = Offset(x = 200.dp.toPx(), y = 200.dp.toPx()) // Center of the circle
//
//        Box(modifier = Modifier.size(400.dp)) {
//            items.forEachIndexed { index, item ->
//                val angle = (2 * PI / items.size) * index
//                val xOffset = (radius * cos(angle)).toDp()
//                val yOffset = (radius * sin(angle)).toDp()
//
//                Box(
//                    modifier = Modifier
//                        .size(40.dp)
//                        .offset(x = center.x.toDp() + xOffset - 20.dp, y = center.y.toDp() + yOffset - 20.dp)
//                        .background(Color.Red)
//                ) {
//                    Text(
//                        text = item,
//                        style = TextStyle(color = Color.White, fontSize = 16.sp, fontWeight = FontWeight.Bold),
//                        modifier = Modifier.align(Center)
//                    )
//                }
//            }
//        }
//    }


    @Composable
    fun Text1() {
        Text(text = "Hello, World!", style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(16.dp),)
    }
    @Composable
    fun Text2() {
        Text(text = "Hello, World!", style = MaterialTheme.typography.bodyLarge)
    }

    @Composable
    fun CardExample(a:Int) {
        Card(
            modifier = Modifier.padding(16.dp),
            shape = RoundedCornerShape(a.dp)
        ) {
            Text(
                text = "Card Content",
                modifier = Modifier.padding(16.dp)
            )
        }
    }

    @Composable
    fun CircularProgressIndicatorExample() {
        Box(modifier = Modifier.size(400.dp,400.dp)) {
            CircularProgressIndicator(modifier = Modifier.align(Center))
        }
    }

    @Composable
    fun CheckboxExample() {
        var checkedState by remember { mutableStateOf(false) }

        Row(modifier = Modifier.padding(16.dp)) {
            Checkbox(
                checked = checkedState,
                onCheckedChange = { checkedState = it }
            )
            Text(
                text = "Check me!",
                modifier = Modifier.padding(start = 8.dp)
            )
        }
    }

    @Composable
    fun TextFieldExample() {
        var text by remember { mutableStateOf("Hello") }
        BasicTextField(
            value = text,
            onValueChange = { newText -> text = newText },
            modifier = Modifier.padding(16.dp)
        )
    }

    @Composable
    fun StyledText() {
        Text(
            text = "Styled Text",
            style = MaterialTheme.typography.headlineMedium.copy(
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.primary
            )
        )
    }

    @Composable
    fun RowLayout() {
        Row(
            modifier = Modifier.padding(16.dp)
        ) {
            Text("Item 1", style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(end = 8.dp))
            Text("Item 2", style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(end = 8.dp))
            Text("Item 3", style = MaterialTheme.typography.bodyLarge)
        }
    }

    @Composable
    fun SimpleButton() {
        Button(onClick = { /* Handle click */ }) {
            Text("Click Me")
        }
    }


    @Composable
    fun LightColorSchemeButton() {
        MaterialTheme(
            colorScheme = lightColorScheme()
        ) {
            Button(onClick = { /* Handle click */ }) {
                Text("Dark Themed Button")
            }
        }
    }


    @Composable
    fun DarkColorSchemeButton() {
        MaterialTheme(
            colorScheme = darkColorScheme()
        ) {
            Button(onClick = { /* Handle click */ }) {
                Text("Dark Themed Button")
            }
        }
    }


    @Composable
    fun SimpleCanvasDrawCircle() {
        Canvas(modifier = Modifier.size(200.dp)) {
            // Draw a circle
            drawCircle(
                color = Color.Blue,
                radius = size.minDimension / 2
            )
        }
    }

    @Composable
    fun SimpleCanvasDrawRect() {
        Canvas(modifier = Modifier
            .size(200.dp)
            .padding(start = 20.dp)) {
            // Draw a circle
            drawRect(
                color = Color(0xff667788),
                topLeft = Offset(10.0f,5.0f),
                        size = Size(200.0f,200.0f)
            )
        }
    }

    @Composable
    fun LineAndPathDrawingCanvas() {
        Canvas(modifier = Modifier.size(300.dp)) {
            // Draw a line
            drawLine(
                color = Color.Black,
                start = Offset(0f, 0f),
                end = Offset(size.width, size.height),
                strokeWidth = 4.dp.toPx()
            )

            // Draw a custom path
            val path = Path().apply {
                moveTo(50f, 50f)
                quadraticBezierTo(size.width / 2, 0f, size.width, size.height)
                lineTo(0f, size.height)
                close()
            }
            drawPath(
                path = path,
                color = Color.Cyan,
                style = Stroke(width = 4.dp.toPx())
            )
        }
    }

    @Composable
    fun AnimatedCanvas() {
        val infiniteTransition = rememberInfiniteTransition()
        val animatedValue by infiniteTransition.animateFloat(
            initialValue = 0f,
            targetValue = 200f,
            animationSpec = infiniteRepeatable(
                animation = tween(2000, easing = LinearEasing),
                repeatMode = RepeatMode.Reverse
            ), label = "1"
        )

        Canvas(modifier = Modifier.size(200.dp)) {
            drawCircle(
                color = Color.Blue,
                radius = animatedValue,
                center = Offset(size.width / 2, size.height / 2)
            )
        }
    }

    @Composable
    fun CustomSurface() {
        Surface(
            modifier = Modifier.padding(16.dp),
            shape = RoundedCornerShape(16.dp),
            color = Color.White,
            contentColor = Color.Black,
            shadowElevation = 8.dp
        ) {
            // Content inside the surface
            Text(
                text = "This is a custom Surface",
                modifier = Modifier.padding(16.dp)
            )
        }
    }

    @Composable
    fun ContentColor() {
        Surface(
            modifier = Modifier.padding(16.dp),
            shape = RoundedCornerShape(16.dp),
            contentColor = Color.Green,
            shadowElevation = 8.dp
        ) {
            // Content inside the surface
            Text(
                text = "contentColor is Green ",
                modifier = Modifier.padding(16.dp)
            )
        }
    }

    @Composable
    fun ContentColor2() {
        Surface(
            modifier = Modifier.padding(16.dp),
            shape = RoundedCornerShape(16.dp),
            contentColor = Color.Yellow,
            shadowElevation = 8.dp
        ) {
            // Content inside the surface
            Text(
                text = "contentColor is Yellow",
                modifier = Modifier.padding(16.dp)
            )
        }
    }

    @Composable
    fun ShadowElevation0() {
        Surface(
            modifier = Modifier.padding(16.dp),
            shape = RoundedCornerShape(16.dp),
            color = Color.White,
            shadowElevation = 0.dp
        ) {
            // Content inside the surface
            Text(
                text = "ShadowElevation 0 ",
                modifier = Modifier.padding(16.dp)
            )
        }
    }

    @Composable
    fun ShadowElevation01() {
        Surface(
            modifier = Modifier.padding(16.dp),
            shape = RoundedCornerShape(16.dp),
            color = Color.White,
            shadowElevation = 2.dp
        ) {
            // Content inside the surface
            Text(
                text = "ShadowElevation is 2",
                modifier = Modifier.padding(16.dp)
            )
        }
    }

    @Composable
    fun ShadowElevation02() {
        Surface(
            modifier = Modifier.padding(16.dp),
            shape = RoundedCornerShape(16.dp),
            color = Color.White,
            shadowElevation = 12.dp
        ) {
            Text(
                text = "ShadowElevation is 12",
                modifier = Modifier.padding(16.dp)
            )
        }
    }

    @Composable
    fun ClickableCard(onClick: () -> Unit) {
        Card(
            modifier = Modifier
                .padding(16.dp)
                .clickable { onClick() },
            elevation = CardDefaults.cardElevation(4.dp)
        ) {
            Text(
                text = "Clickable Card",
                modifier = Modifier.padding(16.dp)
            )
        }
    }

    @Composable
    fun BasicSliderExample() {
        var sliderPosition by remember { mutableStateOf(0f) }

        Column(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxSize(),
            verticalArrangement = Arrangement.Center
        ) {
            Text(text = "Slider Value: ${sliderPosition.toInt()}")
            Slider(
                value = sliderPosition,
                onValueChange = { value -> sliderPosition = value },
                valueRange = 0f..100f
            )
        }
    }

    @Composable
    fun BasicSwitchExample() {
        // State to track the switch's state
        val (isChecked, onCheckedChange) = remember { mutableStateOf(false) }

        Column(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxSize()
        ) {
            Text(text = if (isChecked) "Switch is ON" else "Switch is OFF")
            Switch(
                checked = isChecked,
                onCheckedChange = onCheckedChange
            )
        }
    }

    @Composable
    fun DeterminateCircularProgressIndicatorExample() {
        var progress by remember { mutableStateOf(0.5f) } // Example progress value

        Column(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxSize(),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = CenterHorizontally
        ) {
            CircularProgressIndicator(
                progress = progress, // Determinate progress
                color = Color.Green,
                strokeWidth = 6.dp
            )

            // Example to simulate progress update
            Spacer(modifier = Modifier.height(16.dp))
            Button(onClick = { progress = (progress + 0.1f).coerceAtMost(1f) }) {
                Text(text = "Increase Progress")
            }
        }
    }

    @Composable
    fun CustomColorAndStrokeCircularProgressIndicator() {
        Column(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxSize(),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = CenterHorizontally
        ) {
            CircularProgressIndicator(
                color = Color.Blue, // Custom color
                strokeWidth = 8.dp // Custom stroke width
            )
        }
    }

    @Composable
    fun BasicAlertDialogExample() {
        // State to control the visibility of the dialog
        var showDialog by remember { mutableStateOf(false) }

        Column(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxSize(),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = CenterHorizontally
        ) {
            Button(onClick = { showDialog = true }) {
                Text(text = "Show Dialog")
            }

            if (showDialog) {
                AlertDialog(
                    onDismissRequest = { showDialog = false },
                    title = { Text(text = "Alert Dialog Title") },
                    text = { Text(text = "This is a simple alert dialog example.") },
                    confirmButton = {
                        Button(onClick = { showDialog = false }) {
                            Text("OK")
                        }
                    },
                    dismissButton = {
                        Button(onClick = { showDialog = false }) {
                            Text("Cancel")
                        }
                    }
                )
            }
        }
    }

    @Composable
    fun  LazyColumn01() {
        LazyColumn(modifier = Modifier
            .height(200.dp)
            .background(Color.LightGray)) {
            // Add a single item
            item {
                Text(text = "First item")
            }
            // Add 5 items
            items(500) { index ->
                Text(text = "Item: $index")
            }
            // Add another single item
            item {
                Text(text = "Last item")
            }
        }
    }

    @Composable
    fun BasicLazyColumn() {
        val items = listOf("beijing", "shenzhen", "shanghai")
        LazyColumn(modifier = Modifier
            .height(200.dp)
            .background(Color(0xFF996644))) {
            item {
                Text(text = "header",modifier = Modifier.padding(16.dp))
            }
            items(items) { item ->
                Text(text = item, modifier = Modifier.padding(16.dp))
            }
        }
    }


    @Composable
    fun  LazyColumn02() {
        val items = List(50) { "Item #$it" }
        LazyColumn(modifier = Modifier
            .height(200.dp)
            .background(Color.Red),
        ) {
            items(items) { item ->
                Text(
                    text = item,
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.padding(vertical = 8.dp)
                )
            }
        }
    }

    @Composable
    fun  LazyColumn03() {
        val items = List(50) { "Item #$it" }
        LazyColumn(modifier = Modifier
            .height(200.dp)
            .background(Color(0xFF667788)),
            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 0.dp),
        ) {
            items(items) { item ->
                Text(
                    text = item,
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.padding(vertical = 8.dp)
                )
            }
        }
    }

    @Composable
    fun  LazyColumn04() {
        val items = List(50) { "Item #$it" }
        LazyColumn(modifier = Modifier
            .height(200.dp)
            .background(Color(0xFF6677ff)),
            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
        ) {
            items(items) { item ->
                Text(
                    text = item,
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.padding(vertical = 8.dp)
                )
            }
        }
    }

    @Composable
    fun  LazyColumn05() {
        val items = List(50) { "Item #$it" }
        LazyColumn(modifier = Modifier
            .height(200.dp)
            .background(Color(0xFFff7788)),
            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
            verticalArrangement = Arrangement.spacedBy(4.dp),
            ) {
            items(items) { item ->
                Text(
                    text = item,
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.padding(vertical = 8.dp)
                )
            }
        }
    }

    @Composable
    fun BasicPopupDemo() {
        val showPopup = remember { mutableStateOf(false) }
        Box(
            contentAlignment = Alignment.Center,
            modifier = Modifier
                .height(300.dp)
                .fillMaxWidth()
                .background(Color(0xff667788))
        ) {
            Button(onClick = { showPopup.value = true }) {
                Text(text = "Show Popup")
            }

            if (showPopup.value) {
                Popup(
                    alignment= Alignment.TopStart,
                    onDismissRequest = { showPopup.value = false }) {
                    Box(
                        modifier = Modifier
                            .padding(20.dp)
                            .padding(50.dp)
                            .clickable { showPopup.value = false }
                    ) {
                        Text(text = "This is a basic popup")
                    }
                }
            }
        }
    }

    @Composable
    fun BasicPopupDemo02() {
        val showPopup = remember { mutableStateOf(false) }

        Box(
            contentAlignment = Alignment.Center,
            modifier = Modifier
                .height(300.dp)
                .fillMaxWidth()
                .background(Color(0xff667788))
        ) {
            Button(onClick = { showPopup.value = true }) {
                Text(text = "Show Popup")
            }

            if (showPopup.value) {
                Popup(
                    alignment= Alignment.Center,
                    onDismissRequest = { showPopup.value = false }) {
                    Box(
                        modifier = Modifier
                            .padding(20.dp)
                            .padding(50.dp)
                            .clickable { showPopup.value = false }
                    ) {
                        Text(text = "This is a basic popup")
                    }
                }
            }
        }
    }

    @Composable
    fun BasicPopupDemo03() {
        val showPopup = remember { mutableStateOf(false) }

        Box(
            contentAlignment = Alignment.Center,
            modifier = Modifier
                .height(300.dp)
                .fillMaxWidth()
                .background(Color(0xff667788))
        ) {
            Button(onClick = { showPopup.value = true }) {
                Text(text = "Show Popup")
            }

            if (showPopup.value) {
                Popup(
                    alignment= Alignment.BottomCenter,
                    onDismissRequest = { showPopup.value = false }) {
                    Box(
                        modifier = Modifier
                            .padding(20.dp)
                            .padding(50.dp)
                            .clickable { showPopup.value = false }
                    ) {
                        Text(text = "This is a basic popup")
                    }
                }
            }
        }
    }

    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    fun DatePickerDocked() {
        var showDatePicker by remember { mutableStateOf(false) }
        val datePickerState = rememberDatePickerState()
        val selectedDate = datePickerState.selectedDateMillis?.let {
            convertMillisToDate(it)
        } ?: ""

        Box(
            modifier = Modifier.fillMaxWidth()
        ) {
            OutlinedTextField(
                value = selectedDate,
                onValueChange = {
                    showDatePicker = false
                },
                label = { Text("DOB") },
                readOnly = true,
                trailingIcon = {
                    IconButton(onClick = { showDatePicker = !showDatePicker }) {
                        Icon(
                            imageVector = Icons.Default.DateRange,
                            contentDescription = "Select date"
                        )
                    }
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(64.dp)
            )

            if (showDatePicker) {
                Popup(
                    onDismissRequest = { showDatePicker = false },
                    alignment = Alignment.TopStart
                ) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .offset(y = 64.dp)
                            .shadow(elevation = 4.dp)
                            .background(MaterialTheme.colorScheme.surface)
                            .padding(16.dp)
                    ) {
                        DatePicker(
                            state = datePickerState,
                            showModeToggle = false,
                        )
                    }
                }
            }
        }
    }

    fun convertMillisToDate(millis: Long): String {
        val formatter = SimpleDateFormat("MM/dd/yyyy", Locale.getDefault())
        return formatter.format(Date(millis))
    }

    @Composable
    fun IconButtonDemo(onClick: () -> Unit = {}) {
        IconButton(onClick = onClick) {
            Icon(
                imageVector = Icons.Filled.Favorite,
                contentDescription = "Favorite",
                tint = MaterialTheme.colorScheme.primary
            )
        }
    }

    @Composable
    fun IconWithoutTintDemo() {
        IconButton(onClick = {}) {
            Icon(
                imageVector = Icons.Filled.ThumbUp,
                contentDescription = "Like"
                // No tint applied, so the icon's default color is used
            )
        }
    }

    @Composable
    fun IconWithTintDemo() {
        IconButton(onClick = {}) {
            Icon(
                imageVector = Icons.Filled.ThumbUp,
                contentDescription = "Like",
                tint = Color.Red // Tint applied, changing the icon's color to red
            )
        }
    }

    @Composable
    fun CustomIconButtonDemo(onClick: () -> Unit = {}) {
        IconButton(
            onClick = onClick,
            modifier = Modifier.size(50.dp)
        ) {
            Icon(
                imageVector = Icons.Filled.ThumbUp,
                contentDescription = "Like",
                tint = MaterialTheme.colorScheme.secondary
            )
        }
    }

    @Composable
    fun BasicOutlinedTextField() {
        val text = remember { mutableStateOf("你好") }

        OutlinedTextField(
            value = text.value,
            onValueChange = { text.value = it },
            label = { Text("Enter text") }
        )
    }

    @Composable
    fun BasicOutlinedTextField02() {
        val text = remember { mutableStateOf("你好") }
        OutlinedTextField(
            isError =  true,
            value = text.value,
            onValueChange = { text.value = it },
        )
    }

    @Composable
    fun BasicOutlinedTextField03() {
        val text = remember { mutableStateOf("你好") }
        OutlinedTextField(
            isError =  true,
            value = text.value,
            onValueChange = { text.value = it },
        )
    }

    @Composable
    fun OutlinedTextFieldWithError() {
        val text = remember { mutableStateOf("") }
        val hasError = remember { mutableStateOf(true) }
        OutlinedTextField(
            value = text.value,
            onValueChange = {
                text.value = it
                hasError.value = false
                            },
            label = { Text("Enter text") },
            isError = hasError.value,
        )
    }

    @Composable
    fun OutlinedTextFieldWithPlaceholder() {
        val text = remember { mutableStateOf("") }

        OutlinedTextField(
            value = text.value,
            onValueChange = { text.value = it },
            label = { Text("Enter text") },
            placeholder = { Text("Placeholder text") },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text)
        )
    }


    @Composable
    fun KeyboardTypeNumber() {
        val text = remember { mutableStateOf("") }

        OutlinedTextField(
            value = text.value,
            onValueChange = { text.value = it },
            label = { Text("Enter text") },
            placeholder = { Text("Placeholder text") },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
        )
    }

    @Composable
    fun KeyboardTypePhone() {
        val text = remember { mutableStateOf("") }

        OutlinedTextField(
            value = text.value,
            onValueChange = { text.value = it },
            label = { Text("Enter Phone Number") },
            placeholder = { Text("Placeholder text") },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone)
        )
    }

    @Composable
    fun KeyboardTypeNumberPassword() {
        val text = remember { mutableStateOf("") }

        OutlinedTextField(
            value = text.value,
            onValueChange = { text.value = it },
            label = { Text("Enter Password") },
            placeholder = { Text("Placeholder text") },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),
                    visualTransformation = PasswordVisualTransformation()
        )
    }

    @Composable
    fun KeyboardTypeNumberPassword02() {
        val text = remember { mutableStateOf("") }

        OutlinedTextField(
            value = text.value,
            onValueChange = { text.value = it },
            label = { Text("Enter Password") },
            placeholder = { Text("Placeholder text") },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),
            visualTransformation = PasswordVisualTransformation('*')
        )
    }



    @Composable
    fun OutlinedTextFieldWithCustomTextStyle() {
        val text = remember { mutableStateOf("") }

        OutlinedTextField(
            value = text.value,
            onValueChange = { text.value = it },
            label = { Text("Enter text", style = TextStyle(fontSize = 50.sp)) }
        )
    }

    @Composable
    fun OutlinedTextFieldWithLeadingIcon() {
        val text = remember { mutableStateOf("") }

        OutlinedTextField(
            value = text.value,
            onValueChange = { text.value = it },
            label = { Text("Search") },
            leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) }
        )
    }

    @Composable
    fun OutlinedTextFieldWithTrailingIcon() {
        val text = remember { mutableStateOf("") }

        OutlinedTextField(
            value = text.value,
            onValueChange = { text.value = it },
            label = { Text("Enter text") },
            trailingIcon = {
                Icon(Icons.Filled.Clear, contentDescription = "Clear text", modifier = Modifier.clickable { text.value = "" })
            }
        )
    }

    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    fun DatePickerModal(
        onDateSelected: (Long?) -> Unit = {},
        onDismiss: () -> Unit  = {}
    ) {
        val datePickerState = rememberDatePickerState()
        val show  = remember { mutableStateOf(true) }
        if(show.value) {
            DatePickerDialog(
                onDismissRequest = onDismiss,
                confirmButton = {
                    TextButton(onClick =
                    {
                        this
                        show.value= false
                        onDateSelected(datePickerState.selectedDateMillis)
                        onDismiss()
                    }) {
                        Text("OK")
                    }
                },
                dismissButton = {
                    TextButton(onClick = onDismiss) {
                        Text("Cancel")
                    }
                }
            ) {
                DatePicker(state = datePickerState)
            }
        }
    }

    @OptIn(ExperimentalMaterial3Api::class)
    @Preview
    @Composable
    fun DatePickerSample() {
        val a = remember {
              mutableStateOf(true)
        }
        if(a.value) {
            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                // Pre-select a date for January 4, 2020
                val datePickerState =
                    rememberDatePickerState(initialSelectedDateMillis = 1578096000000)
                DatePicker(state = datePickerState, modifier = Modifier.padding(16.dp))

                Text(
                    "Selected date timestamp: ${datePickerState.selectedDateMillis ?: "no selection"}",
                    modifier = Modifier.align(Alignment.CenterHorizontally)
                )
                
                Button(onClick = {  a.value = false }) {
                    Text(text = "OK")
                }
            }
        }
    }



    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    fun DatePickerDialogSample(openDialog:MutableState<Boolean>) {
        // Decoupled snackbar host state from scaffold state for demo purposes.
        val snackState = remember { SnackbarHostState() }
        val snackScope = rememberCoroutineScope()
        SnackbarHost(hostState = snackState, Modifier)

        // TODO demo how to read the selected date from the state.
        if (openDialog.value) {
            val datePickerState = rememberDatePickerState()
            val confirmEnabled = remember {
                derivedStateOf { datePickerState.selectedDateMillis != null }
            }
            DatePickerDialog(
                onDismissRequest = {
                    // Dismiss the dialog when the user clicks outside the dialog or on the back
                    // button. If you want to disable that functionality, simply use an empty
                    // onDismissRequest.
                    openDialog.value = false
                },
                confirmButton = {
                    TextButton(
                        onClick = {
                            openDialog.value = false
                            snackScope.launch {
                                snackState.showSnackbar(
                                    "Selected date timestamp: ${datePickerState.selectedDateMillis}"
                                )
                            }
                        },
                        enabled = confirmEnabled.value
                    ) {
                        Text("OK")
                    }
                },
                dismissButton = {
                    TextButton(onClick = { openDialog.value = false }) { Text("Cancel") }
                }
            ) {
                DatePicker(state = datePickerState)
            }
        }
    }


    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    fun DatePickerWithDateSelectableDatesSample() {
        val datePickerState =
            rememberDatePickerState(
                selectableDates =
                object : SelectableDates {
                    // Blocks Sunday and Saturday from being selected.
                    override fun isSelectableDate(utcTimeMillis: Long): Boolean {
                        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            val dayOfWeek =
                                Instant.ofEpochMilli(utcTimeMillis)
                                    .atZone(ZoneId.of("UTC"))
                                    .toLocalDate()
                                    .dayOfWeek
                            dayOfWeek != DayOfWeek.SUNDAY && dayOfWeek != DayOfWeek.SATURDAY
                        } else {
                            val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
                            calendar.timeInMillis = utcTimeMillis
                            calendar[Calendar.DAY_OF_WEEK] != Calendar.SUNDAY &&
                                    calendar[Calendar.DAY_OF_WEEK] != Calendar.SATURDAY
                        }
                    }

                    // Allow selecting dates from year 2023 forward.
                    override fun isSelectableYear(year: Int): Boolean {
                        return year > 2022
                    }
                }
            )

        Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
            DatePicker(state = datePickerState)
            Text(
                "Selected date timestamp: ${datePickerState.selectedDateMillis ?: "no selection"}",
                modifier = Modifier.align(Alignment.CenterHorizontally)
            )
        }
    }

    @OptIn(ExperimentalMaterial3Api::class)
    @Preview
    @Composable
    fun DateInputSample() {
        Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
            val state = rememberDatePickerState(initialDisplayMode = DisplayMode.Input)
            DatePicker(state = state, modifier = Modifier.padding(16.dp))

            Text(
                "Entered date timestamp: ${state.selectedDateMillis ?: "no input"}",
                modifier = Modifier.align(Alignment.CenterHorizontally)
            )
        }
    }




    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e("FirstFragment","MainActivity  onCreate");
        setContent {
            MaterialTheme {
                Surface() {
                    val openDialog = remember { mutableStateOf(true) }

                    Column( modifier = Modifier
                        .fillMaxSize()
                        .verticalScroll(rememberScrollState())
                        .padding(8.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp)) {

//                        DateInputSample()

//                        Button(onClick = {
//                            openDialog.value = true
//                        } ,
//                        ){ Text("Click Me")}
                        //ok
//                        DatePickerDialogSample(openDialog)
                        //ok
//                        DatePickerWithDateSelectableDatesSample()
                        //ok
//                        DatePickerSample()
                        //ok
//                        DatePickerModal();


                        KeyboardTypeNumberPassword()
                        KeyboardTypeNumberPassword02()

                        OutlinedTextFieldWithTrailingIcon()
                        OutlinedTextFieldWithLeadingIcon()
                        BasicOutlinedTextField()
                        BasicOutlinedTextField02()
                        BasicOutlinedTextField03()
                        OutlinedTextFieldWithError()
                        OutlinedTextFieldWithPlaceholder()
                        OutlinedTextFieldWithCustomTextStyle()
                        KeyboardTypeNumber()
                        KeyboardTypePhone()

                        CustomIconButtonDemo()

                        IconWithoutTintDemo()
                        IconWithTintDemo()

                        IconButtonDemo{
                        }

                        DatePickerDocked()



                        BasicPopupDemo()
                        BasicPopupDemo02()
                        BasicPopupDemo03()
                        LazyColumn01()
                        BasicLazyColumn()
                        Row{
                            LazyColumn02()
                            LazyColumn03()
                            LazyColumn04()
                            LazyColumn05()
                        }

                        CustomColorAndStrokeCircularProgressIndicator()
                        DeterminateCircularProgressIndicatorExample()
                        BasicAlertDialogExample()
                        CustomSurface()
                        ContentColor()
                        ContentColor2()
                        ShadowElevation0()
                        ShadowElevation01()
                        ShadowElevation02()
                        ClickableCard{}
                        Spacer(modifier = Modifier.height(20.dp))
                        BasicSliderExample()
                        BasicSwitchExample()

                        Text1()
                        Text2()
                        CardExample(0)
                        CardExample(1)
                        CheckboxExample()
                        TextFieldExample()
                        StyledText()
                        RowLayout()
                        SimpleButton()
                        DarkColorSchemeButton()
                        LightColorSchemeButton()
                        SimpleCanvasDrawCircle()
                        SimpleCanvasDrawRect()
                        LineAndPathDrawingCanvas()
                        AnimatedCanvas()

                        CircularProgressIndicatorExample()
                    }
                }
            }
        }





//        binding = ActivityMainBinding.inflate(layoutInflater)
//        setContentView(binding.root)
//
//        setSupportActionBar(binding.toolbar)


//        if (savedInstanceState == null) {
//            supportFragmentManager.beginTransaction()
//                .add(R.id.fragment_container, a, "1")
//                .commit()
//        }

//        val navController = findNavController(R.id.nav_host_fragment_content_main)
//        appBarConfiguration = AppBarConfiguration(navController.graph)
//        setupActionBarWithNavController(navController, appBarConfiguration)

//        binding.fab.setOnClickListener { view ->
////            replaceFragment(b,"2");
////            val fragmentManager: FragmentManager = supportFragmentManager
////            val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
////            fragmentTransaction.hide(b)
////            fragmentTransaction.show(a);
////            fragmentTransaction.commit();
//
//
//            val fragmentManager = supportFragmentManager
//            val fragmentTransaction = fragmentManager.beginTransaction()
//            fragmentTransaction.replace(R.id.fragment_container, a, "1")
//            fragmentTransaction.addToBackStack("1")
//            fragmentTransaction.commit()




//            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                .setAction("Action", null)
//                .setAnchorView(R.id.fab).show()
//            try{
//                navController.navigate(R.id.action_FirstFragment_to_Fragment03);
//
//            }catch (_:Exception){
//
//            }

//            Log.e("111",""+navController.currentDestination?.displayName);






//            navController.findDestination("1111").


        }


//        binding.fab2.setOnClickListener { view ->
////            replaceFragment(a,"1");
////            val fragmentManager: FragmentManager = supportFragmentManager
////            val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
////            fragmentTransaction.hide(a)
////            fragmentTransaction.commit();
//
//
//            val fragmentManager = supportFragmentManager
//            val fragmentTransaction = fragmentManager.beginTransaction()
//            fragmentTransaction.replace(R.id.fragment_container, b, "2")
//            fragmentTransaction.addToBackStack("2")
//            fragmentTransaction.commit()


//            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                .setAction("Action", null)
//                .setAnchorView(R.id.fab).show()
//            try{
//                navController.navigate(R.id.action_FirstFragment_to_Fragment03);
//
//            }catch (_:Exception){
//
//            }

//            Log.e("111",""+navController.currentDestination?.displayName);






//            navController.findDestination("1111").


//        }
//    }


//    fun replaceFragment(fragment: Fragment, tag: String) {
//        val fragmentManager: FragmentManager = supportFragmentManager
//        val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
//        fragmentTransaction.replace(R.id.fragment_container, fragment, tag)
//        fragmentTransaction.addToBackStack(tag)
//        fragmentTransaction.commit()
//    }
//
//    override fun onCreateOptionsMenu(menu: Menu): Boolean {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        menuInflater.inflate(R.menu.menu_main, menu)
//        return true
//    }
//
//    override fun onOptionsItemSelected(item: MenuItem): Boolean {
//        // Handle action bar item clicks here. The action bar will
//        // automatically handle clicks on the Home/Up button, so long
//        // as you specify a parent activity in AndroidManifest.xml.
//        return when (item.itemId) {
//            R.id.action_settings -> true
//            else -> super.onOptionsItemSelected(item)
//        }
//    }

//    override fun onSupportNavigateUp(): Boolean {
////        val navController = findNavController(R.id.nav_host_fragment_content_main)
////        return navController.navigateUp(appBarConfiguration)
////                || super.onSupportNavigateUp()
//    }

    companion object{
//        val  a = FirstFragment();
//        val  b = SecondFragment();
    }
}